// Socket封装
//import defines from './defines'
import EventListener from '../communal/EventListener';

const SocketControlle = ()=>{
    let that = {};
    // 当前类的Socket
    let _socket = undefined;
    let _callBackIndex = 1;
    let _callBackMap = {};
    let _event = EventListener({});

    // 初始化网络环境
    that.init = ()=>{
        _socket = io(defines.ServerUrl);
        _socket.on('notify', (data)=>{
            let callBackIndex = data.callBackIndex;
            let msg = data.msg;
            _event.fire(msg, data.data);
            let cb = _callBackMap[callBackIndex];
            if (cb){
                cc.log('data = ' + JSON.stringify(data.data));
                if (data.data.err) {
                    cb(data.data.err);
                } else {
                    cb(null, data.data);
                }
                
            }
        });
    };

    // 网络发送数据
    const notify = (msg, data)=>{
        _socket.emit('notify', {msg: msg, callBackIndex: _callBackIndex, data: data});
        _callBackIndex++;
    };

    // 网络发送数据
    const request = (msg, data, cb)=>{
        _callBackMap[_callBackIndex] = cb;
        notify(msg, data);
    };

    // 发送登录数据
    that.login = (unique, name, url, cb)=>{
        request('login', {uniqueID: unique, nickName: name, avatarUrl: url}, cb);
    };

    // 创建房间消息
    that.creatorRoom = (data, cb)=>{
        request('creator_room', data, cb);
    };

    // 加入房间消息
    that.joinRoom = (roomID, cb)=>{
        request('join_room', {joinRoomID: roomID}, cb)
    };

    // 监听服务器登陆后发来的玩家信息处理
    that.loginPlayerInfo = ()=>{
        
    };

    return that;
};

export default SocketControlle;